import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:read_flutter_test/main.dart';

import '../bean/BookStyle.dart';
import '../bean/book.dart';
import '../bean/font_model.dart';
import '../service/player_service.dart';
import '../utils/webView/webview_console_message.dart';
import '../utils/webView/webview_initial_variable.dart';
import '../widgets/reading_page/style_widget.dart';

class EpubPlayer extends StatefulWidget {
  final Book book;
  final String? cfi;
  final Function showOrHideAppBarAndBottomBar;
  final Function onLoadEnd;

  const EpubPlayer({super.key,
    required this.showOrHideAppBarAndBottomBar,
    required this.book,
    this.cfi,
    required this.onLoadEnd});

  @override
  State<EpubPlayer> createState() => EpubPlayerState();
}

class EpubPlayerState extends State<EpubPlayer> {
  late InAppWebViewController webViewController;
  late ContextMenu contextMenu;
  late Book book;

  String indexHtmlPath =
      "http://localhost:${Server().port}/foliate-js/index.html";


  @override
  void initState() {
    super.initState();
    book = widget.book;
    contextMenu = ContextMenu(
      settings: ContextMenuSettings(hideDefaultSystemContextMenuItems: true),
      onCreateContextMenu: (hitTestResult) async {
        print("显示Menu");
        // webViewController.evaluateJavascript(source: "showContextMenu()");
      },
      onHideContextMenu: () {
        // removeOverlay();
        print("隐藏Menu");
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      child: InAppWebView(
        webViewEnvironment: webViewEnvironment,
        initialUrlRequest: URLRequest(url: WebUri(indexHtmlPath)),
        initialSettings: initialSettings,
        contextMenu: contextMenu,
        onConsoleMessage: (controller, consoleMessage) {
          if (consoleMessage.message.contains('loadBook')) {
            onWebViewCreated(controller);
          }
          webviewConsoleMessage(controller, consoleMessage);
        },
      ),
    );
  }

  Future<void> onWebViewCreated(InAppWebViewController controller) async {
    if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
      await InAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
    print('@@@ onWebViewCreated');
    webViewController = controller;
    setHandler(controller);
  }

  //webView的事件处理
  Future<void> setHandler(InAppWebViewController controller) async {
    String uri = Uri.encodeComponent(widget.book.fileFullPath);
    String url = 'http://localhost:${Server().port}/book/$uri';
    String initialCfi = widget.cfi ?? widget.book.lastReadPosition;
    webviewInitialVariable(
      controller,
      url,
      initialCfi,
      backgroundColor:"#FFFFFF",
      textColor:"#000000",
    );


  }

  InAppWebViewSettings initialSettings = InAppWebViewSettings(
    supportZoom: false,
    transparentBackground: true,
    isInspectable: kDebugMode,
  );
  // void removeOverlay(){
  //   if(contextMenuEntry == null)
  // }

  void changePageTurnStyle(PageTurn pageTurnStyle) {
    webViewController.evaluateJavascript(source: '''
      changeStyle({
        pageTurnStyle: '${pageTurnStyle.name}',
      })
    ''');
  }

  void changeFont(FontModel font) {
    webViewController.evaluateJavascript(source: '''
      changeStyle({
        fontName: '${font.name}',
        fontPath: '${font.path}',
      })
    ''');
  }



  //页内行间距
  void changeStyle(BookStyle bookStyle) {
    // styleTimer?.cancel();
    // styleTimer = Timer(const Duration(milliseconds: 300), () {
    //   webViewController.evaluateJavascript(source: '''
    //   changeStyle({
    //     fontSize: ${bookStyle.fontSize},
    //     spacing: ${bookStyle.lineHeight},
    //     fontWeight: ${bookStyle.fontWeight},
    //     paragraphSpacing: ${bookStyle.paragraphSpacing},
    //     topMargin: ${bookStyle.topMargin},
    //     bottomMargin: ${bookStyle.bottomMargin},
    //     sideMargin: ${bookStyle.sideMargin},
    //     letterSpacing: ${bookStyle.letterSpacing},
    //     textIndent: ${bookStyle.indent},
    //     maxColumnCount: ${bookStyle.maxColumnCount},
    //   })
    //   ''');
    // });
  }

}
